//
//  FXEmoticonCollectionViewCell.swift
//  微博(Swift)
//
//  Created by V on 16/1/13.
//  Copyright © 2016年 V. All rights reserved.
//

import UIKit

// 一页最大的列数与行数
let FXEmoticonKeyboardPageMaxCol = 7
let FXEmoticonKeyboardPageMaxRow = 3
// 一页显示的表情个数
let FXEmoticonKeyboardCountOfPage = FXEmoticonKeyboardPageMaxCol * FXEmoticonKeyboardPageMaxRow - 1

class FXEmoticonCollectionViewCell: UICollectionViewCell {
    // MARK: - 属性
    var indexPath: NSIndexPath? {
        didSet{
            // testLabel.text = "第\(indexPath!.section)组，第\(indexPath!.item)页"
        }
    }
    // emoticons 存的是20个表情图片的名字
    var emoticons: [FXEmoticon]? {
        didSet {
            // 这里设置隐藏的目的：只有在cell有button的时候才能够显示出button，防止最近表情页面的cell重用别的表情页面，导致数据错位。但是emoji表情因为自身有button，所以这里设置button的隐藏属性不能避免cell的重用导致的数据错位
            for value in emoticonButtons {
                value.hidden = true
            }
            for (i, value) in emoticons!.enumerate() {
                let button = emoticonButtons[i]
                button.hidden = false
                button.emoticon = value
            }
        }
    }
    
    
    
    // MARK: - 懒加载
    private lazy var testLabel: UILabel = UILabel(textColor: UIColor.blackColor(), fontSize: 35)
    private lazy var emoticonButtons: [FXEmoticonButton] = [FXEmoticonButton]()
    // 删除按钮
    private lazy var deleteButton: UIButton = {
        let button = UIButton()
        button.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
        button.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
        return button
    }()
    // popView
    private lazy var popView: FXEmoticonPopView = FXEmoticonPopView.popView()

    
    
    // MARK: - 初始化
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 这里通常设置子控件的 frame
    override func layoutSubviews() {
        let itemW = (self.frame.width - 10) / CGFloat(FXEmoticonKeyboardPageMaxCol)
        let itemH =  (self.frame.height - 20) / CGFloat(FXEmoticonKeyboardPageMaxRow)
        for (i, value) in emoticonButtons.enumerate() {
            let col = i % FXEmoticonKeyboardPageMaxCol
            let row = i / FXEmoticonKeyboardPageMaxCol
            // x,y
            value.frame.origin.x = CGFloat(col) * itemW + 5
            value.frame.origin.y = CGFloat(row) * itemH
            // 大小
            value.frame.size = CGSize(width: itemW, height: itemH)
        }
        // 删除按钮的frame，size
        deleteButton.frame = CGRect(x: self.frame.width - itemW - 5, y: 2 * itemH, width: itemW, height: itemH)
    }
    
    
    
    // MARK: - 设置UI
    private func setupUI() {
        // 注意子控件的添加顺序，顺序决定子控件的层次
        // 添加20个表情button和一个删除按钮
        addEmotion()
        self.addSubview(testLabel)
        // 在 cell 中添加子控件最好用 contentView ，如果使用 addSubview(testLabel) 可能会出现子控件的约束不对。
        /// contentView 和 self 打印出来的不是一个frame，如果用contentView的时候会出现位置错位，但是使用self就不会出现。
        // print(contentView)
        // print(self)
        testLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self)
        }
    }
    
    // 添加20个表情,和一个删除按钮
    private func addEmotion() {
        for _ in 0..<FXEmoticonKeyboardCountOfPage {
            let button = FXEmoticonButton()
            // 点击 button 弹出popView
            button.addTarget(self, action: "emoticonButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)

            button.backgroundColor = UIColor.clearColor()
            self.addSubview(button)
            emoticonButtons.append(button)
            // print(contentView)
        }
        contentView.addSubview(deleteButton)
        // 创建长按手势
        let ges = UILongPressGestureRecognizer(target: self, action: "longPress:")
        // 添加手势
        addGestureRecognizer(ges)
    }
    
    
    @objc private func emoticonButtonClick(button: FXEmoticonButton) {
        // 发送通知：传递点击的按钮
        NSNotificationCenter.defaultCenter().postNotificationName(FXEmoticonDidSelectedNotification, object: button.emoticon)
        let pop = FXEmoticonPopView.popView()
        let window = UIApplication.sharedApplication().windows.last!
        // 坐标转换，将一个视图在坐标转换到另外一个视图里面
        let rect = button.superview?.convertRect(button.frame, toView: window)
        pop.center.x = CGRectGetMidX(rect!)
        pop.frame.origin.y = CGRectGetMinY(rect!) - button.frame.height
        window.addSubview(pop)
        let emoticon = button.emoticon
        pop.emoticon = emoticon
        // 延迟取消
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.25 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            pop.removeFromSuperview()
        }
    }
    
    
    
    // 长按手势调用的方法
    @objc private func longPress(ges: UIGestureRecognizer) {
        // 1.获取手指的位置
        func buttonWithLocation(location: CGPoint) ->FXEmoticonButton? {
            for button in emoticonButtons {
                if CGRectContainsPoint(button.frame, location) {
                    // print(button.emoticon)
                    return button
                }
            }
            return nil
        }
        // 手指在当前View的位置
        let location = ges.locationInView(self)
        // 2.获取手指位置的button的emoctino
        guard let button = buttonWithLocation(location) else {
            return
        }
        // 3.添加popView
        let state = ges.state
        switch state {
        case .Began, .Changed:
            let window = UIApplication.sharedApplication().windows.last
            // print(UIApplication.sharedApplication().windows)
            let rect = button.superview!.convertRect(button.frame, fromView: window)
            // print(button.superview)
            // print(button.superview!)
            popView.center.x = CGRectGetMidX(rect)
            popView.frame.origin.y = SCREENH - self.frame.height + button.frame.origin.y  - button.frame.height * 2 + 18
            popView.emoticon = button.emoticon
            // print(popView)
            window?.addSubview(popView)
        case .Ended, .Cancelled :
            popView.removeFromSuperview()
        default:
            popView.removeFromSuperview()
        }
    }
}
